﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Reflection;
using System.Web.Compilation;

namespace UIT.Web
{
	public class Application : HttpApplication
	{
		static internal UIT.Application application;
		public Application()
		{
			UIT.Context.GetContext = () => new Context(HttpContext.Current);
		}

		private void Application_Start(object sender, EventArgs e)
		{
			PageHandlerFactory.EnsureExecutingAssemblyInitialized();
			Type applicationType = null;
			if (PageHandlerFactory.ExecutingAssembly == null)
			{
				foreach (Assembly assembly in BuildManager.GetReferencedAssemblies())
				{
					if ((applicationType = assembly.GetExportedTypes().FirstOrDefault(t => t.BaseType == typeof(UIT.Application))) != null)
					{
						PageHandlerFactory.ExecutingAssembly = assembly;
						break;
					}
				}
			}
			else
				applicationType = PageHandlerFactory.ExecutingAssembly.GetExportedTypes().FirstOrDefault(t => t.BaseType == typeof(UIT.Application));

			if (applicationType != null)
			{
				application = (UIT.Application)Activator.CreateInstance(applicationType);

				application.OnStart();
			}
		}

		private void Application_End(object sender, EventArgs e)
		{
			if (application != null)
				application.OnStop();
		}
	}
}
